/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.IllegalOrphanException;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Gallery;
import java.util.HashSet;
import java.util.Set;
import shmallarchitect.jpa.entities.Locum;
import java.util.ArrayList;
import shmallarchitect.jpa.entities.Owner;

/**
 *
 * @author jaccus
 */
public class OwnerJpaController {
    @Resource(mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Owner owner) throws RollbackFailureException, Exception {
        if (owner.getGalleries() == null) {
            owner.setGalleries(new HashSet<Gallery>());
        }
        if (owner.getLocums() == null) {
            owner.setLocums(new HashSet<Locum>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Set<Gallery> attachedGalleries = new HashSet<Gallery>();
            for (Gallery galleriesGalleryToAttach : owner.getGalleries()) {
                galleriesGalleryToAttach = em.getReference(galleriesGalleryToAttach.getClass(), galleriesGalleryToAttach.getId());
                attachedGalleries.add(galleriesGalleryToAttach);
            }
            owner.setGalleries(attachedGalleries);
            Set<Locum> attachedLocums = new HashSet<Locum>();
            for (Locum locumsLocumToAttach : owner.getLocums()) {
                locumsLocumToAttach = em.getReference(locumsLocumToAttach.getClass(), locumsLocumToAttach.getId());
                attachedLocums.add(locumsLocumToAttach);
            }
            owner.setLocums(attachedLocums);
            em.persist(owner);
            for (Gallery galleriesGallery : owner.getGalleries()) {
                Owner oldOwnerOfGalleriesGallery = galleriesGallery.getOwner();
                galleriesGallery.setOwner(owner);
                galleriesGallery = em.merge(galleriesGallery);
                if (oldOwnerOfGalleriesGallery != null) {
                    oldOwnerOfGalleriesGallery.getGalleries().remove(galleriesGallery);
                    oldOwnerOfGalleriesGallery = em.merge(oldOwnerOfGalleriesGallery);
                }
            }
            for (Locum locumsLocum : owner.getLocums()) {
                Owner oldOwnerOfLocumsLocum = locumsLocum.getOwner();
                locumsLocum.setOwner(owner);
                locumsLocum = em.merge(locumsLocum);
                if (oldOwnerOfLocumsLocum != null) {
                    oldOwnerOfLocumsLocum.getLocums().remove(locumsLocum);
                    oldOwnerOfLocumsLocum = em.merge(oldOwnerOfLocumsLocum);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Owner owner) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Owner persistentOwner = em.find(Owner.class, owner.getId());
            Set<Gallery> galleriesOld = persistentOwner.getGalleries();
            Set<Gallery> galleriesNew = owner.getGalleries();
            Set<Locum> locumsOld = persistentOwner.getLocums();
            Set<Locum> locumsNew = owner.getLocums();
            List<String> illegalOrphanMessages = null;
            for (Locum locumsOldLocum : locumsOld) {
                if (!locumsNew.contains(locumsOldLocum)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Locum " + locumsOldLocum + " since its owner field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Set<Gallery> attachedGalleriesNew = new HashSet<Gallery>();
            for (Gallery galleriesNewGalleryToAttach : galleriesNew) {
                galleriesNewGalleryToAttach = em.getReference(galleriesNewGalleryToAttach.getClass(), galleriesNewGalleryToAttach.getId());
                attachedGalleriesNew.add(galleriesNewGalleryToAttach);
            }
            galleriesNew = attachedGalleriesNew;
            owner.setGalleries(galleriesNew);
            Set<Locum> attachedLocumsNew = new HashSet<Locum>();
            for (Locum locumsNewLocumToAttach : locumsNew) {
                locumsNewLocumToAttach = em.getReference(locumsNewLocumToAttach.getClass(), locumsNewLocumToAttach.getId());
                attachedLocumsNew.add(locumsNewLocumToAttach);
            }
            locumsNew = attachedLocumsNew;
            owner.setLocums(locumsNew);
            owner = em.merge(owner);
            for (Gallery galleriesOldGallery : galleriesOld) {
                if (!galleriesNew.contains(galleriesOldGallery)) {
                    galleriesOldGallery.setOwner(null);
                    galleriesOldGallery = em.merge(galleriesOldGallery);
                }
            }
            for (Gallery galleriesNewGallery : galleriesNew) {
                if (!galleriesOld.contains(galleriesNewGallery)) {
                    Owner oldOwnerOfGalleriesNewGallery = galleriesNewGallery.getOwner();
                    galleriesNewGallery.setOwner(owner);
                    galleriesNewGallery = em.merge(galleriesNewGallery);
                    if (oldOwnerOfGalleriesNewGallery != null && !oldOwnerOfGalleriesNewGallery.equals(owner)) {
                        oldOwnerOfGalleriesNewGallery.getGalleries().remove(galleriesNewGallery);
                        oldOwnerOfGalleriesNewGallery = em.merge(oldOwnerOfGalleriesNewGallery);
                    }
                }
            }
            for (Locum locumsNewLocum : locumsNew) {
                if (!locumsOld.contains(locumsNewLocum)) {
                    Owner oldOwnerOfLocumsNewLocum = locumsNewLocum.getOwner();
                    locumsNewLocum.setOwner(owner);
                    locumsNewLocum = em.merge(locumsNewLocum);
                    if (oldOwnerOfLocumsNewLocum != null && !oldOwnerOfLocumsNewLocum.equals(owner)) {
                        oldOwnerOfLocumsNewLocum.getLocums().remove(locumsNewLocum);
                        oldOwnerOfLocumsNewLocum = em.merge(oldOwnerOfLocumsNewLocum);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = owner.getId();
                if (findOwner(id) == null) {
                    throw new NonexistentEntityException("The owner with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Owner owner;
            try {
                owner = em.getReference(Owner.class, id);
                owner.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The owner with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Set<Locum> locumsOrphanCheck = owner.getLocums();
            for (Locum locumsOrphanCheckLocum : locumsOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Owner (" + owner + ") cannot be destroyed since the Locum " + locumsOrphanCheckLocum + " in its locums field has a non-nullable owner field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Set<Gallery> galleries = owner.getGalleries();
            for (Gallery galleriesGallery : galleries) {
                galleriesGallery.setOwner(null);
                galleriesGallery = em.merge(galleriesGallery);
            }
            em.remove(owner);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Owner> findOwnerEntities() {
        return findOwnerEntities(true, -1, -1);
    }

    public List<Owner> findOwnerEntities(int maxResults, int firstResult) {
        return findOwnerEntities(false, maxResults, firstResult);
    }

    private List<Owner> findOwnerEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Owner as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Owner findOwner(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Owner.class, id);
        } finally {
            em.close();
        }
    }

    public int getOwnerCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Owner as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
